package net.ncraft.mc.easyframework.configuration;

import net.ncraft.mc.easyframework.FunctionRegister;
import net.ncraft.mc.easyframework.LeadLoading;
import net.ncraft.mc.easyframework.configuration.anno.BukkitConfiguration;
import net.ncraft.mc.easyframework.configuration.core.EasyConfiguration;
import net.ncraft.mc.easyframework.context.ApplicationContext;
import net.ncraft.mc.easyframework.context.anno.Autowired;
import net.ncraft.mc.easyframework.context.anno.Component;
import org.apache.commons.io.FileUtils;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

@Component
public class BukkitConfigurationRegister implements FunctionRegister , LeadLoading {
    @Autowired
    private ApplicationContext context;
    @Autowired
    private JavaPlugin plugin;
    @Override
    public void register() {
        for (Class<?> component : context.getComponents()) {
            if (!EasyConfiguration.class.isAssignableFrom(component)) continue;
            if (!component.isAnnotationPresent(BukkitConfiguration.class)) continue;
            String configName = component.getAnnotation(BukkitConfiguration.class).value();
            if (configName.isEmpty()) throw new RuntimeException(component.getName() + " ,Configuration name is empty");
            File configDir = plugin.getDataFolder();
            if (!configDir.exists()) configDir.mkdir();
            File configFile = new File(configDir, configName);
            if (!configFile.exists()) {
                InputStream resource = plugin.getResource(configName);
                try {
                    if (resource != null) {
                        FileUtils.copyInputStreamToFile(resource, configFile);
                        FileConfiguration config = new YamlConfiguration();
                        config.load(configFile);
                        context.updateBean(component, config);
                        context.reAutowire();
                    } else {
                        throw new RuntimeException(configName + " , Configuration file not found");
                    }
                } catch (IOException | InvalidConfigurationException e) {
                    throw new RuntimeException(e);
                }
            }else {
                try {
                    FileConfiguration config = new YamlConfiguration();
                    config.load(configFile);
                    context.updateBean(component, config);
                    context.reAutowire();
                } catch (IOException | InvalidConfigurationException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    @Override
    public void init() {
        register();
    }
}
